let app = getApp(); 
var mqtt = require('../../utils/mqtt.js')
var util = require('../../utils/util.js')
const host = app.globalData.mqtt_host;//连接的服务器域名，注意格式！！！
Page({
  data: {
    sae: null,
    equipment:[],
    num:0,
    timer:'',
    client: null,
    time:0,
    reconnectCounts: 0,//记录重连的次数
    options: { //MQTT连接的配置
      protocolVersion: 4, //MQTT连接协议版本
      clientId: wx.getStorageSync('openid'),
      clean: false,
      password: '',
      username: '',
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
      Retained:false
    }
  },
  onLoad: function () {// 页面渲染后 执行
    this.equipment_data()
  },
  onPullDownRefresh: function() {// 触发下拉刷新时执行
    this.equipment_data()
  },
  equipment_data:function(){//获取绑定设备信息
    var that = this;
    if(wx.getStorageSync('topic')&&wx.getStorageSync('topic')!="failure"){
      wx.request({
        url: app.globalData.equipment_url,
        data: {
          openid: wx.getStorageSync('openid')
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: function (res) {
          console.log(res)
          console.log(res.data.length)
          var clientId="options.clientId"
          that.setData({
            equipment:res.data,
            num:res.data.length,
            [clientId]:wx.getStorageSync('openid')
          }) 
        },
      })
      this.mqtt_coti()
      this.sendCode()
    }else{
      
      that.setData({
        num:false,
      }) 
    }
  },
  onShow: function() {    // 页面出现在前台时执行
    
  },
  sendCode: function(e) { //定时任务
    var that = this
    var i = setInterval(function() {
      var timestamp = Date.parse(new Date());  
      timestamp = timestamp / 1000; 
      for(var i=0;i<that.data.num;i++){
      var t = timestamp - that.data.equipment[i].time
      var image_2 = 'equipment['+i+'].image_2'
      var time = 'equipment['+i+'].time'
      console.log("当前时间差：" + t); 
      if(t>20){
        that.setData({
          [image_2]:'../../png/wifi_wu.png',
          [time]:0,
        })
      }
    }
    }, 15000)
  },
  onClick_open: function(e) {//打开
    var that = this
    console.log('控制代号：'+e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index
    /*var str = "equipment[" + index + "].image_1"//重点在这里，组合出一个字符串
    this.setData({
      [str]: '../../png/denglv.png'//用中括号把str括起来即可
    })*/
    console.log('当前time：'+that.data.equipment[index].time);
    if (that.data.equipment[index].time > 0) {
     var news = '{"applianceId":'+ that.data.equipment[index].applianceId+app.globalData.open_mes
      this.data.client.publish(wx.getStorageSync('topic')+'1',news );
      console.log("控制成功")
    } else {
      wx.showToast({
        title: '控制失败,设备离线',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onClick_shut: function(e) {//关闭
    var that =this
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index
    console.log(that.data.equipment[index].time);
    if (that.data.equipment[index].time != 0) {
      console.log("控制成功")
      var news = '{"applianceId":'+ that.data.equipment[index].applianceId+app.globalData.shut_mes
      this.data.client.publish(wx.getStorageSync('topic')+'1', news);
    } else {
      wx.showToast({
        title: '控制失败，设备离线',
        icon: 'none',
        duration: 2000
      })
    }
  },
  mqtt_coti: function(){
    var equipment = this.data
    var that =this
    this.data.client = mqtt.connect(host, this.data.options);//开始连接
    this.data.client.on('connect', function(connack) {
      console.log('连接成功')
    })
    this.data.client.on('message', function (topic,payload) {//服务器下发消息的回调
      if(topic == wx.getStorageSync('topic')+'0'){
        console.log(topic)
        console.log(payload)
        var jsonObj = JSON.parse(payload)
        console.log(jsonObj.applianceId)
        for(var i=0; i<that.data.num;i++){
          var image_1 = 'equipment['+i+'].image_1'
          var lamp = 'equipment['+i+'].lamp'
          var image_2 = 'equipment['+i+'].image_2'
          var time = 'equipment['+i+'].time'
          //console.log(equipment.equipment[i].applianceId)
          if(jsonObj.applianceId == equipment.equipment[i].applianceId){
            //console.log(i)
            if(jsonObj.control == "off"){
              that.setData({
                [image_1]:'../../png/denghong.png',
                [lamp]:'onClick_open'
              })
            }
            if(jsonObj.control == "on"){
              that.setData({
                [image_1]:'../../png/denglv.png',
                [lamp]: 'onClick_shut'
              })
            }
            if(jsonObj.state == 1){
              var timestamp = Date.parse(new Date());  
              timestamp = timestamp / 1000;  
              //console.log("当前时间戳为：" + timestamp);  
              var TIME = util.formatTime(new Date())
              that.setData({
                [image_2]:'../../png/wifi_lv.png',
                [time]:timestamp,
              })
              console.log(TIME)
            }
          }
        }
      }
    })   
    this.data.client.on("error", function(error) {//服务器连接异常的回调
      console.log(" 服务器错误的回调" + error)
    })  
    this.data.client.on("reconnect", function() {//服务器重连连接异常的回调
      console.log(" 服务器重新连接异常的回调")
    })     
    this.data.client.on("offline", function(errr) {//服务器连接异常的回调
      console.log("连接异常")
    })  
    this.data.client.subscribe(wx.getStorageSync('topic')+'0', function(err, granted) {//订阅
      if (!err) {
        console.log("订阅成功"+wx.getStorageSync('topic')+'0')
      } else {
        console.log("订阅失败")
      }
    })       
  },  
/*add_:function(){
    wx.navigateTo({
      url: '../add_device/add_device',
    })
  }*/

  changeToggle(){
    var that = this;
    that.setData({
      isShow:!that.data.isShow
    })
  },


})